"""
边界约束系统
处理单位的边界约束和突破检测

作者：wjttdbx
版本：3.0 - 重构版本，使用工具模块
"""
import sys
sys.path.insert(0, sys.path[0]+"/../")

import math
from typing import TYPE_CHECKING
from .config import GameConfig
from .utils import (
    POLYGON_POINTS, point_in_polygon, point_to_line_segment_nearest_point,
    is_in_battle_area, check_breakthrough
)

if TYPE_CHECKING:
    from .units import Unit, BlackBoat


class BoundarySystem:
    """
    边界约束系统
    
    处理单位在凸八边形边界内的约束和突破检测
    """

    @staticmethod
    def enforce_boundaries(unit: 'Unit'):
        """
        强制单位在凸八边形边界内

        Args:
            unit (Unit): 要约束的单位
        """
        # 使用工具模块的函数检查是否在边界内
        if not is_in_battle_area(unit.x, unit.y):
            # 如果出界，将单位移到最近的边界上
            BoundarySystem._move_to_nearest_boundary(unit)

    @staticmethod
    def _move_to_nearest_boundary(unit: 'Unit'):
        """将单位移动到最近的边界上"""
        min_distance = float('inf')
        closest_x, closest_y = unit.x, unit.y

        # 对每条边进行投影，找到最近点
        for i in range(len(POLYGON_POINTS)):
            p1 = POLYGON_POINTS[i]
            p2 = POLYGON_POINTS[(i + 1) % len(POLYGON_POINTS)]

            # 计算点到线段的最近点
            nearest_x, nearest_y = point_to_line_segment_nearest_point(
                unit.x, unit.y, p1[0], p1[1], p2[0], p2[1])

            distance = math.sqrt((unit.x - nearest_x)**2 + (unit.y - nearest_y)**2)
            if distance < min_distance:
                min_distance = distance
                closest_x, closest_y = nearest_x, nearest_y

        # 将单位移动到边界上，稍微向内偏移避免边界振荡
        direction_x = unit.x - closest_x
        direction_y = unit.y - closest_y
        length = math.sqrt(direction_x**2 + direction_y**2)
        
        if length > 0:
            # 向内偏移100米
            offset = 100
            unit.x = closest_x + (direction_x / length) * offset
            unit.y = closest_y + (direction_y / length) * offset
        else:
            unit.x = closest_x
            unit.y = closest_y

    @staticmethod
    def check_breakthrough(black_boat: 'BlackBoat') -> bool:
        """
        检查黑方无人艇是否突破封锁线

        Args:
            black_boat (BlackBoat): 黑方无人艇

        Returns:
            bool: 是否突破封锁线
        """
        # 使用工具模块的函数检查突破
        if check_breakthrough(black_boat.x):
            black_boat.crossed = True
            # 突破后自动消失
            black_boat.active = False
            if GameConfig.debug_mode:
                print(f"[BoundarySystem] 黑方无人艇{black_boat.id} 突破封锁线，自动消失")
            return True
        return False
